package badge

import (
	"sort"
	"time"

	"gddgame.cc/galaxy/common/dsl/game"
)

const SettingBadgeName = "setting_badge"

// 确保依赖badge在前面
// 基础badge最好引用战斗数据
type SettingBadge struct {
	Id         int               `json:"id" orm:"auto" sql:"INT"`
	ParentId   int               `json:"parent_id" sql:"INT"`
	Type       int               `json:"type" sql:"TINYINT"`
	Name       map[string]string `json:"name" sql:"JSON"`
	Desc       map[string]string `json:"desc" sql:"JSON"`
	Icon       string            `json:"icon" sql:"VARCHAR"`
	Way        map[string]string `json:"way" sql:"JSON"`
	Factors    []game.Factor     `json:"factors" sql:"JSON"`
	Score      int               `json:"score" sql:"INT"`
	Level      int               `json:"level" sql:"INT"`
	StartTime  *time.Time        `json:"start_time" sql:"DATETIME"`
	ExpireTime *time.Time        `json:"expire_time" sql:"DATETIME"`

	// 扩展参数：游戏端
	Extend interface{} `json:"extend" sql:"JSON"`
	// 扩展参数：服务端
	Inside interface{} `json:"inside" sql:"JSON"`

	UpdateTime *time.Time `json:"update_time" orm:"updateTime" sql:"DATETIME"`

	children BadgeSlice
	goal     int32
}

func (badge *SettingBadge) Append(child *SettingBadge) {
	if badge.children == nil {
		badge.children = []*SettingBadge{}
	}
	badge.children = badge.children.Append(child)
}

func (badge *SettingBadge) Children() []*SettingBadge {
	if badge.children == nil {
		return []*SettingBadge{}
	}
	return badge.children
}

func (badge *SettingBadge) GetLevel(level int) *SettingBadge {
	if level == 0 {
		return badge
	}
	if level > len(badge.children) {
		return nil
	}
	return badge.children[level-1]
}

func (badge *SettingBadge) List() []*SettingBadge {
	if badge.children == nil {
		return []*SettingBadge{badge}
	}
	return badge.children
}

func (badge *SettingBadge) GetGoal() int32 {
	if badge.goal > 0 {
		return badge.goal
	}
	badge.goal = int32(0)
	for _, factor := range badge.Factors {
		badge.goal += factor.Value
	}
	return badge.goal
}

type BadgeSlice []*SettingBadge

func (p BadgeSlice) Len() int           { return len(p) }
func (p BadgeSlice) Less(i, j int) bool { return p[i].Level < p[j].Level }
func (p BadgeSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p BadgeSlice) Sort()              { sort.Sort(p) }
func (l BadgeSlice) Append(t *SettingBadge) BadgeSlice {
	ll := append(l, t)
	ll.Sort()
	return ll
}
